package com.shujia.flink.tf

import org.apache.flink.api.common.functions.FlatMapFunction
import org.apache.flink.streaming.api.scala._
import org.apache.flink.util.Collector

object Demo2FlatMap {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val linesDS: DataStream[String] = env.readTextFile("flink/data/words.txt")

    // java api
    val wordsDS: DataStream[String] = linesDS.flatMap(new FlatMapFunction[String, String] {

      /**
       * flatMap:传入一条数据返回多条数据
       *
       * @param value ：一条数
       * @param out   ：用于将数据发送到下游，没执行一次，发送一条
       */
      override def flatMap(value: String, out: Collector[String]): Unit = {
        val split: Array[String] = value.split(",")

        for (word <- split) {
          //将数据发送到下游
          out.collect(word)
        }
      }
    })

    //scala api
    linesDS.flatMap(_.split(","))


    wordsDS.print()

    env.execute()
  }

}
